package middleware

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"goAdminV1/utility"
	"strings"
)

// 定义上下文键
const (
	ContextUserIDKey   = "user_id"
	ContextUsernameKey = "username"
)

const (
	ErrCodeNoToken = 10001
)

// JwtAuth JWT 校验中间件
func JwtAuth(r *ghttp.Request) {
	// 从请求头中获取 token
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		r.Response.WriteJson(g.Map{
			"code":    ErrCodeNoToken,
			"message": "未提供 Token",
			"data":    nil,
		})
		r.ExitAll()
	}
	// 去除 Bearer 前缀
	parts := strings.SplitN(authHeader, " ", 2)
	if len(parts) != 2 || parts[0] != "Bearer" {
		r.Response.WriteJson(g.Map{
			"code":    ErrCodeNoToken,
			"message": "无效的 Authorization 头格式",
			"data":    nil,
		})
		r.ExitAll()
	}
	token := strings.TrimSpace(parts[1]) // 去除 Token 左右的空格和换行

	// 解析 Token
	claims, err := utility.ParseToken(r.Context(), token)
	if err != nil {
		r.Response.WriteJson(g.Map{
			"code":    ErrCodeNoToken,
			"message": "Token 无效或已过期",
			"data":    nil,
		})
		r.ExitAll()
	}

	// 将用户 ID 和用户名存储在请求的上下文中
	ctx := r.Context()
	ctx = context.WithValue(ctx, ContextUserIDKey, claims.UserID)
	ctx = context.WithValue(ctx, ContextUsernameKey, claims.Username)
	r.SetCtx(ctx)
	// 继续执行后续逻辑
	r.Middleware.Next()
}
